package com.cq.common.config.shiro;

import com.cq.model.SysRole;
import com.cq.model.SysUser;
import com.cq.service.SysRoleService;
import com.cq.service.SysUserService;
import com.cq.utils.SpringUtils;
import com.cq.utils.UserUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定账户密码匹配 方便以后扩展
 *
 * @author zhouqi
 */
public class MyShiroRealm extends AuthorizingRealm {


    private static final Logger logger = LoggerFactory.getLogger(MyShiroRealm.class);

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysUser sysUser = (SysUser) principalCollection.getPrimaryPrincipal();
        SysRoleService sysRoleService = SpringUtils.getBean(SysRoleService.class);
        SysRole sysRole = sysRoleService.getById(sysUser.getRole());
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 添加角色
        logger.info("本次登陆用户的权限为{}", sysRole.getCode());
        authorizationInfo.addRole(sysRole.getCode());
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        MyUsernamePasswordToken usernamePasswordToken = (MyUsernamePasswordToken) token;
        String username = ((MyUsernamePasswordToken) token).getUsername();
        // 获取SysUserService实例
        SysUserService sysUserService = SpringUtils.getBean(SysUserService.class);
        SysUser sysUser = sysUserService.getByUsername(username);
        if (sysUser == null) {
            throw new UnknownAccountException("用户名不存在");
        }
        if (!sysUser.getPassword().equals(sysUserService.passwordEncoder(new String(usernamePasswordToken.getPassword()), sysUser.getUsername()))) {
            throw new IncorrectCredentialsException("密码错误");
        }
        ByteSource bytes = ByteSource.Util.bytes(sysUser.getUsername());
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(sysUser, sysUser.getPassword(), bytes, getName());
        UserUtils.setUserSession(sysUser);
        return authenticationInfo;
    }
}
